<?php

/**
 * Zend_Controller_action, Neues Spiel anlegen, Punkte eines Spiels speichern
 * @author  Christian Greweling, Sascha Witte
 */
class GameController extends Zend_Controller_Action {

    protected $explicitCatanTypeMapper = null;
    protected $userMapper = null;
    protected $catanMapper;
    protected $pointMapper;

    public function init() {
        $this->_statusMessenger = $this->_helper->flashMessenger;
        $this->_errorMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
        $this->_errorMessenger->setNamespace('error');
        $this->view->statusMessages = $this->_statusMessenger->getMessages();
        $this->view->errorMessages = $this->_errorMessenger->getMessages();
        $this->explicitCatanTypeMapper = new Application_Model_ExplicitCatanTypeMapper();
        $this->userMapper = new Application_Model_UserMapper();
        $this->pointMapper = new Application_Model_ExplicitCatanPointsMapper();
        $this->view->headScript()->appendFile('/resources/jscript/chosen/chosen.jquery.min.js');
    }

    public function indexAction() {
        
    }

    /*
     * Hinzufuegen eines Speiltyps und Usern
     */

    public function addAction() {


        $this->view->headTitle('Create new Game');
        $this->view->documentClasses = array('game', 'add');
        $this->view->headScript()->appendScript('
                $(document).ready(function() {
                       $(".chzn-select").chosen();
                });
        ');
        $post = $this->_request->getPost();
        $this->view->form;

        array($params);
        $params = $this->_request->getParams();

        $_event = $this->_request->getParam('id');
        $this->view->form = $this->_getAddForm($_event);


        if ($post && false !== $this->_request->getPost('submit', false)) {
            if (!$this->view->form->isValid($params)) {
                $this->view->form->populate($this->_request->getParams());
            } else {
                $sessionNamespace = new Zend_Session_Namespace();
                $sessionNamespace->array = array();
                $sessionNamespace->array = $this->_request->getPost();
                $this->_redirect('game/edit?id=' . $_event);
            }
        }
    }

    /**
     * Ergebnisse des Spiels eintragen 
     * Punkte der Benutzer, welche Sieg eigenschaften
     * wer gewonnen hat
     * Abhängig von den Eintragungen in ExplicitCatanTypeModel
     */
    public function editAction() {
        //Daten vom vorherigen Formular aus Session auslesen
        $sessionNamespace = new Zend_Session_Namespace();
        $values = $sessionNamespace->array;

        $this->_helper->viewRenderer('edit');
        $this->view->headTitle('Edit Results');

        // Javascript das nach selektieren der hoechsten Siegpunktzahl den richtige Gewinner auswaehlt.
        /*
          $this->view->headScript()->appendScript('
          var value = 0;
          var winner = "";
          $(document).ready(function() {
          $("#points input:radio").click(function() {
          if (value < $(this).val()){
          value = $(this).val();
          winner = $(this).attr("name")
          $("input[name=\'radio-button-gruppe\'][value=\'2\']").attr("checked","checked");
          }

          });
          });
          ');
         */
        $this->view->documentClasses = array('game', 'edit');
        $post = $this->_request->getPost();


        foreach ($values['user'] as $u) {
            $user[] = $this->userMapper->find($u, new Application_Model_UserModel);
        }

        $gameType = $this->explicitCatanTypeMapper->find($values['gameType'], new Application_Model_ExplicitCatanTypeModel);
        $this->view->users = $user;
        $this->view->form = $this->_getEditForm($user, $gameType, $values['eventId']);


        if ($post && false !== $this->_request->getPost('abspeichern', false)) {
            if (!$this->view->form->isValid($post)) {
                $this->view->form->populate($post);
            } else {

                $this->save();
            }
        }
    }

    /**
     * Speichern der eingegeben Spiel-Ergebnisse
     * in die Datenbank 
     */
    public function save() {

        $post = $this->_request->getPost();

        $this->catanMapper = new Application_Model_ExplicitCatanMapper();

        if ($post) {
            $values = $this->_request->getParams();

            $game = new Application_Model_ExplicitCatanModel();

            //neues Spiel speichern
            $game->setEvent_id($values['eventId'])
                    ->setType_id($values['gameType'])
                    ->setWinner_id($values['winner']);

            $game = $this->catanMapper->save($game);

            //Punkte Speichern Spieltypen 
            foreach ($values as $key => $value) {
                if ($key == 'hasStreet') {
                    $street = new Application_Model_ExplicitCatanStreetModel();
                    $streetMapper = new Application_Model_ExplicitCatanStreetMapper();
                    $street->setGame_id($game->getId());
                    $street->setUser_id($value);
                    $streetMapper->save($street);
                } else if ($key == 'hasKnight') {
                    $knight = new Application_Model_ExplicitCatanKnightModel();
                    $knightMapper = new Application_Model_ExplicitCatanKnightMapper();
                    $knight->setGame_id($game->getId());
                    $knight->setUser_id($value);
                    $knightMapper->save($knight);
                } else {
                    $where = 'salutation ="' . $key . '"';
                    $user = $this->userMapper->fetchone($where);
                    if ($user != null) {
                        $point = new Application_Model_ExplicitCatanPointsModel();
                        $point->setGame_id($game->getId());
                        $point->setUser_id($user->getId());
                        $point->setPoints($value);
                        $this->pointMapper->save($point);
                    }
                }
            }


            if (null !== $game->id) {
                $this->_statusMessenger->addMessage(
                        $this->view->translate('Game saved.')
                );
                $this->_redirect('/event/detail?id=' . $values['eventId']);
            } else {
                $this->_errorMessenger->addMessage(
                        $this->view->translate('Error while saving!')
                );
            }
        }
    }

    /**
     * Formular fuer AddAction
     * 
     * @param type $eventId Aktuell ausgewähltes Event(SpieleAbend)
     * @return \Zend_Form 
     */
    protected function _getAddForm($eventId) {
        $form = new Zend_Form();
        $form->setMethod(Zend_Form::METHOD_POST);
        //$form->setAction('/game/edit');
        $gameTypeSelect = new Zend_Form_Element_Select('gameType');
        $gameTypeSelect->setRequired(true)->addValidator('NotEmpty', true)
                ->setAttrib('class', 'chzn-select')
                ->setAttrib('data-placeholder', $this->view->translate('players'));

        $table = new Application_Model_ExplicitCatanTypeMapper();
        $table = $table->fetchAll();
        foreach ($table as $c) {
            $gameTypeSelect->addMultiOption($c->getId(), $c->getName());
        }

        $form->addElement($gameTypeSelect);

        // Vorhandene Benutzer hinzufuegen

        $userSelect = new Zend_Form_Element_Multiselect('user');

        $userSelect->setRequired(true)->addValidator('NotEmpty', true)
                ->setAttrib('class', 'chzn-select')
                ->setAttrib('style', 'width: 400px; height: 40px')
                ->setAttrib('data-placeholder', $this->view->translate('select players'));


        $table = new Application_Model_UserMapper();
        $table = $table->fetchAll(null, 'salutation ASC');
        foreach ($table as $c) {
            $userSelect->addMultiOption($c->getId(), $c->getSalutation());
        }


        $userSelect->addValidator(new ValidateUserCount());

        $db = Zend_Db_Table::getDefaultAdapter();
        $select = new Zend_Db_Select($db);
        $select->from('explicit_catan_points', array(new Zend_Db_Expr('max(explicit_catan_points.game_id) as last')))
                ->joinInner('explicit_catan', 'explicit_catan.id = explicit_catan_points.game_id', array())
                ->joinInner('event', 'explicit_catan.event_id = event.id', array())
                ->where('explicit_catan.event_id = ?', $eventId);


        $lastGameOfThiEevent = $db->fetchOne($select);
        if ($lastGameOfThiEevent) {
            $db = Zend_Db_Table::getDefaultAdapter();
            $select = new Zend_Db_Select($db);
            $select->from('explicit_catan_points', array('explicit_catan_points.user_id'))
                    ->where('explicit_catan_points.game_id = ?', $lastGameOfThiEevent);
            $userid = $db->fetchAll($select);
            $playerDefaults = array();
            foreach ($userid as $u) {

                array_push($playerDefaults, $u[user_id]);
            }
            $userSelect->setValue($playerDefaults);
        }

        $form->addElement($userSelect);

        $form->addElements(array(array('submit', 'submit', array(
                    'label' => _('Create'),
            ))));

        //Formularfeld fuer Werubergabe
        $form->addElements(array(
            array('hidden', 'user_error', array(
            ))));

        $form->addElements(array(
            array('hidden', 'eventId', array(
                    'value' => $eventId,
            ))));
        $form->setDecorators(array('Viewhelper'));
        $form->removeDecorator('Label');
        $form->removeDecorator('HtmlTag');
        return $form;
    }

    /**
     * Form fuer EditAction
     * 
     * @param type $user array der aktuellem UserModels
     * @param type $gameType ExplicitCatanTypeModel =>Spieltyp 
     * @param type $eventId Id des Events =>Spieleabend
     * @return \Zend_Form 
     */
    protected function _getEditForm($user, $gameType, $eventId) {

        $form = new Zend_Form();
        $form->setMethod(Zend_Form::METHOD_POST);
        // user mit selektboxen anlegen 
        foreach ($user as $u) {
            $anzahl = (int) $gameType->getPoints();
            $multioptionsarray = array();
            for ($i = 2; $i <= $anzahl; $i++) {
                $temp = $u->salutation . $i;
                $multioptionsarray[$i] = $i;
            }
            $form->addElement('radio', $u->salutation, array(
                multiOptions => $multioptionsarray
                , 'separator' => ' ', array('NotEmpty', true), 'required' => true
            ));
        }

        //falls Gametype Option enthaelt RadioButton fuer alle Nutzer erstellen
        if ($gameType->getHas_street()) {


            $hasStreet = new Zend_Form_Element_Radio('hasStreet');
            foreach ($user as $c) {
                $hasStreet->addMultiOption($c->getId(), $c->getSalutation());
            }
            $hasStreet->setLabel($this->view->translate('Street:'));
            $form->addElement($hasStreet);
        }


        if ($gameType->getHas_knight()) {


            $hasKnight = new Zend_Form_Element_Radio('hasKnight');
            ;
            foreach ($user as $c) {
                $hasKnight->addMultiOption($c->getId(), $c->getSalutation());
            }
            $hasKnight->setLabel($this->view->translate('Knight:'));
            $form->addElement($hasKnight);
        }

        $winner = new Zend_Form_Element_Radio('winner');
        $winner->setRequired(true)->addValidator('NotEmpty', true);
        foreach ($user as $c) {
            $winner->addMultiOption($c->getId(), $c->getSalutation());
        }
        $winner->setLabel($this->view->translate('Winner:'));
        $form->addElement($winner);



        $form->addElements(array(array('submit', 'abspeichern', array(
                    'label' => _('Save'),
            ))));

        $form->addElements(array(
            array('hidden', 'eventId', array(
                    'value' => $eventId,
            ))));

        $form->addElements(array(
            array('hidden', 'gameType', array(
                    'value' => $gameType->getId(),
            ))));

        return $form;
    }

}

/*
 * Validiert ob genau so viele Spiele ausgewählt wurden,
 * wie in ExplicitCatanTypeModel->GameTyp angegeben sind
 * 
 */

class ValidateUserCount extends Zend_Validate_Abstract {

    const NOT_MATCH = 'invalid';

    protected $_messageTemplates = array(
        self::NOT_MATCH => 'Falsche Anzahl Spieler für diesen Spieltyp! Zulässig sind: %value% Spieler.'
    );

    public function isValid($value, $array = null) {
        $explicitCatanTypeMapper = new Application_Model_ExplicitCatanTypeMapper();
        $gameType = $explicitCatanTypeMapper->find($array['gameType'], new Application_Model_ExplicitCatanTypeModel);
        $validNumbers = $gameType->getPlayers();
        $validNumbers = explode(';', $validNumbers);
        $countUser = $array['user'];
        $countUser = count($countUser);
        if ($validNumbers != null) {
            foreach ($validNumbers as $n) {
                if ($n == $countUser)
                    return TRUE;
            }
        }
        $this->_error(self::NOT_MATCH, implode(', ', $validNumbers));
        return FALSE;
    }

}

